package thread2;

/**
 * wait/notify/notifyAll
 */
public class WaitTest {

    static Object food = null;

    static void normal() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (food == null) {
                synchronized (WaitTest.class) {
                    System.out.println("no food waiting ...");
                    try {
                        WaitTest.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("get food, go home.");
        });
        thread.start();
        Thread.sleep(2000L);
        food = new Object();
        synchronized (WaitTest.class) {
            System.out.println("wake up the thread");
            WaitTest.class.notify();
        }
    }

    /**
     * deadlock - miss notify
     * @throws InterruptedException
     */
    static void missNotify() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (food == null) {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (WaitTest.class) {
                    try {
                        System.out.println("no food waiting ...");
                        WaitTest.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("get food, go home.");
        });
        thread.start();
        Thread.sleep(2000L);
        food = new Object();
        synchronized (WaitTest.class) {
            System.out.println("wake up the thread");
            WaitTest.class.notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        normal();
        missNotify();
    }
}
